package com.guli.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("login.html")
    public String loginPage(@RequestParam("redirect_url") String redirect_url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token) {
        if(!StringUtils.isEmpty(sso_token)){
            //说明之前有人登录过
            return "redirect:" + redirect_url + "?token=" + sso_token;
        }
        model.addAttribute("url",redirect_url);
        return "login";
    }

    @PostMapping("/dologin")
    public String dologin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功，跳回到之前的页面
            String uuid = UUID.randomUUID().toString().replace("-","");
            stringRedisTemplate.opsForValue().set(uuid,username);
            Cookie sso_token = new Cookie("sso_token",uuid);
            response.addCookie(sso_token);
            return "redirect:" + url + "?token=" + uuid;
        }
        //登录失败
        return "redirect:http://ssoserver.com:8080/login.html?redirect_url=" + url;
    }

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }


}
